import importlib.util

try:
    importlib.util.find_spec('RPi.GPIO')
    import RPi.GPIO as GPIO
except ImportError:
    import FakeRPi.GPIO as GPIO

SIG_HIGH = GPIO.HIGH
SIG_LOW = GPIO.LOW


def gpio_init(mode=GPIO.BCM, warnings=False, in_channels=None, out_channels=None):
    """
    初始化树莓派
    :param mode: 默认BCM
    :param warnings: 默认False
    :param in_channels: 输入管脚列表[data_pin]
    :param out_channels: 输出管脚列表 [[data_pin, initial]]
    :return: void
    """
    GPIO.setmode(mode)
    GPIO.setwarnings(warnings)
    gpio_init_in_channel(in_channels)
    gpio_init_out_channel(out_channels)


def gpio_init_out_channel(out_channels=None):
    if out_channels is None:
        out_channels = []
    if len(out_channels) > 0:
        for out_channel in out_channels:
            GPIO.setup(out_channel[0], GPIO.OUT, initial=out_channel[1])


def gpio_init_in_channel(in_channels=None):
    if in_channels is None:
        in_channels = []
    if len(in_channels) > 0:
        for in_channel in in_channels:
            GPIO.setup(in_channel, GPIO.IN)


def gpio_output(channel, state):
    """
    gpio通用输出方法
    :param channel: bcm编码
    :param state: HIGN or LOW
    :return: void
    """
    GPIO.output(channel, state)


def gpio_input(channel):
    """
    gpio通用输入方法
    :param channel: bcm编码
    :return: HIGN or LOW
    """
    return GPIO.input(channel)


def gpio_cleanup(channels):
    """
    清理管脚
    :param channels: bcm编码
    :return: void
    """
    if channels is None:
        channels = []
    if len(channels) > 0:
        for channel in channels:
            GPIO.cleanup(channel)


def gpio_pmw(channel, frequency):
    GPIO.PWM(channel, frequency)
